import { Divider, ListItem } from '@material-ui/core';
import Avatar from '@material-ui/core/Avatar';
import List from '@material-ui/core/List';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import ListItemText from '@material-ui/core/ListItemText';
import { makeStyles } from '@material-ui/core/styles';
import FolderIcon from '@material-ui/icons/Folder';
import ImageIcon from '@material-ui/icons/Image';
import VideoCallIcon from '@material-ui/icons/VideoCall';
import dayjs from 'dayjs';
import qs from 'qs';
import React, { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { ListItemType } from '.';
import { ErrorDialog } from '../../components/ErrorDialog';
import { Loading } from '../../components/Loading';
import { useDirectory } from '../../context';
import { http, stringifySize } from '../../util';

const useStyles = makeStyles(theme => ({
  root: {
    width: '100%',
    backgroundColor: theme.palette.background.paper,
  },
}));

interface FileListProp {
  keyword: string;
  listData: ListItemType[];
  setListData: (listData: ListItemType[]) => void;
}

export const FileList = ({ keyword, listData, setListData }: FileListProp) => {
  const classes = useStyles();

  const history = useHistory();
  const { directory, setDirectory } = useDirectory();
  const [loading, setLoading] = useState(false);
  const [isError, setIsError] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');
  useEffect(() => {
    setLoading(true);
    http('list', { data: { directory: directory.join('\\') } })
      .then(data => {
        setLoading(false);
        setListData(data.data);
      })
      .catch(e => {
        setLoading(false);
        setIsError(true);
        setErrorMessage(e.message);
      });
  }, [directory, setListData]);

  const handleFolder = (folderName: string) => {
    window.scrollTo(0, 0);
    setDirectory([...directory, folderName]);
    setListData([]);
  };

  return (
    <>
      <List
        className={classes.root}
      >
        {listData
          .filter(item => item.type === 'DIRECTORY' && item.name.includes(keyword))
          .map((folder, index) => (
            <ListItem key={folder.name + index} button onClick={() => handleFolder(folder.name)}>
              <ListItemAvatar>
                <Avatar style={{ color: '#f3d16d', backgroundColor: 'white' }}>
                  <FolderIcon fontSize="large" />
                </Avatar>
              </ListItemAvatar>
              <ListItemText
                primary={folder.name}
                secondary={dayjs(folder.lastModified).format('YYYY年MM月DD日 HH:mm:ss')}
              />
            </ListItem>
          ))}
        <Loading loading={loading} />
        {!loading &&
          listData.find(item => item.type === 'DIRECTORY') &&
          listData.find(item => item.type === 'VIDEO') && <Divider variant="inset" />}
        {listData
          .filter(item => item.type === 'VIDEO' && item.name.includes(keyword))
          .map((video, index) => (
            <ListItem
              key={video.name + index}
              button
              onClick={() =>
                history.push(
                  `/video?${qs.stringify({ directory: directory.join('\\'), name: video.name })}`
                )
              }
            >
              <ListItemAvatar>
                <Avatar style={{ color: '#f55385', backgroundColor: 'white' }}>
                  <VideoCallIcon fontSize="large" />
                </Avatar>
              </ListItemAvatar>
              <ListItemText
                primary={video.name}
                secondary={`${stringifySize(video.size)} | ${dayjs(video.lastModified).format('YYYY年MM月DD日 HH:mm:ss')}`}
              />
            </ListItem>
          ))}
        {!loading &&
          listData.find(item => item.type === 'VIDEO') &&
          listData.find(item => item.type === 'IMAGE') && <Divider variant="inset" />}
        {listData
          .filter(item => item.type === 'IMAGE' && item.name.includes(keyword))
          .map((image, index) => (
            <ListItem
              key={image.name + index}
              button
              onClick={() => {
                window.scrollTo(0, 0);
                history.push(`/image?directory=${directory.join('\\')}&index=${index}`)
              }}
            >
              <ListItemAvatar>
                <Avatar style={{ color: '#a074c4', backgroundColor: 'white' }}>
                  <ImageIcon fontSize="large" />
                </Avatar>
              </ListItemAvatar>
              <ListItemText
                primary={image.name}
                secondary={`${stringifySize(image.size)} | ${dayjs(image.lastModified).format('YYYY年MM月DD日 HH:mm:ss')}`}
              />
            </ListItem>
          ))}
      </List>
      <ErrorDialog isError={isError} setIsError={setIsError} message={errorMessage} />
    </>
  );
};
